#include"SSList.h"
LTNode* LTBuyNode(LTDataType x){
    LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
    if(newnode == NULL){
        perror("malloc fail!");
        exit(1);
    }
    newnode->data = x;
    newnode->next = newnode->prev = newnode;

    return newnode;
}

LTNode* LTInit(){
    LTNode* phead = LTBuyNode(-1);
    return phead;
}

void LTPushBack(LTNode* phead,LTDataType x){
    assert(phead);

    LTNode* newnode = LTBuyNode(x);
    newnode->next = phead;
    newnode->prev = phead->prev;

    phead->prev->next = newnode;
    phead->prev = newnode;
}

void LTPushFront(LTNode* phead,LTDataType x){
    assert(phead);

    LTNode* newnode = LTBuyNode(x);
    newnode->next = phead->next;
    newnode->prev = phead;

    phead->next->prev = newnode;
    phead->next = newnode;
}

void LTPrint(LTNode* phead){
    assert(phead);
    LTNode* pcur = phead->next;
    while(pcur != phead){
        printf("%d->",pcur->data);
        pcur = pcur->next;
    }
    printf("\n");
}

void LTPopBack (LTNode* phead){
    assert(phead);
    assert(phead->next != phead);

    LTNode* del = phead->prev;
    LTNode* prev = del->prev;

    prev->next = phead;
    phead->prev = prev;

    free(del);
    del = NULL;
}

void LTPopFront(LTNode* phead) {
	assert(phead);
	assert(phead->next != phead);

	LTNode* del = phead->next;
	LTNode* next = del->next;

	//phead del next
	next->prev = phead;
	phead->next = next;

	free(del);
	del = NULL;
}

LTNode* LTFind(LTNode* phead,LTDataType x){
    assert(phead);
    LTNode* pcur = phead->next;
    while(pcur != phead){
        if(pcur->data == x){
            return pcur;
        }
        pcur = pcur->next;
    }
    return NULL;
}

//pos位置之后插入数据
void LTInsert(LTNode* pos,LTDataType x){
    assert(pos);
    LTNode* newnode = LTBuyNode(x);
    newnode->next = pos->next;
    newnode->prev = pos;

    pos->next->prev = newnode;
    pos->next = newnode;
}
//删除pos位置的数据
void LTErase(LTNode* pos){
    assert(pos);

    pos->next->prev = pos->prev;
    pos->prev->next = pos->next;

    free(pos);
    pos = NULL;
}

void LTDestroy(LTNode* phead){
    assert(phead);

    LTNode* pcur = phead->next;
    while(pcur != phead){
        LTNode* next = pcur->next;
        free(pcur);
        pcur = next;
    }
    free(phead);
    phead = NULL;
}
